 <template>
  <div style="background: #fff">
    <OverlayContainer :rect="{ x: 100, y: 100, width: 100, height: 100 }">
      <!-- <a-button-group style="position: absolute;top:400px">
      <a-button type="link" size="large" ><b>+</b> </a-button>
      <a-button type="link" size="large"> <b>::</b> </a-button>
      </a-button-group> -->

      <div class="bre-div-h100">
        <div class="markdown-body">
          <div
            class="block-node"
            spellcheck="true"
            contenteditable="true"
            placeholder="输入标题"
          ></div>
        </div>
        <div
          class="markdown-body"
          @keyup.delete="keyupBackspaceDelete"
          @keyup="slashHotKey"
          @mouseleave="removeMenu"
          @mouseover="getMouseenter"
          @keydown.enter="keydownEnter"
          @keydown.up="direction($event, 'up')"
          @keydown.down="direction($event, 'down')"
          @keydown.left="direction($event, 'left')"
          @keydown.right="direction($event, 'right')"
        >
          <!-- KeyboardEvent.key:keydown.shift="direction($event,'down')"  -->
          <!-- draggable="true" -->
          <div
            v-for="(item, _selectIndex) in blockElement.blocks"
            contenteditable
            class="block-node"
            :placeholder="item.placeholder"
            @focus="getInputFocus"
            :selectIndex="_selectIndex"
            :key="item.id"
            v-html="item.html"
          ></div>
          <!-- <div contenteditable="false" class="list-menu"><b><a ><a-icon type="plus-circle" />
            &nbsp;</a><a> ::</a> </b> </div>-->
          <!-- <div class="show-html" ></div> -->
          <!-- <div class="list-menu" v-html="(item.menu)||''"></div> -->
        </div>
        <a-textarea
          :auto-size="{ minRows: 2 }"
          v-model:value="tempText"
          placeholder="textarea with clear icon"
          allow-clear
        />
        <a-button @click="mdRender" type="primary">替换</a-button>
      </div>
    </OverlayContainer>
  </div>
</template>
<script>
import temp from "@/adminCore/views/article/templatedata";
import md from "@/adminCore/views/article/markdwon-it-config";
import { cursor } from "@/adminCore/views/article/cursor";
import { mdTextParsee2 } from "@/adminCore/views/article/importMarkdown";
import OverlayContainer from "@/components/overlay-container/OverlayContainer";
// import DropBox from "@/components/DropBox";

function creatBlock(text, html, menu = "") {
  let o = {};
  let _text = String(text);
  o.html = html;
  o.placeholder = " ";
  o.id = text + String(Math.random());
  o.menu = menu;
  o.text = _text;
  // o.sayName = function () { console.log(this.name); };
  return o;
}
function delEle(ele, i) {
  const delLen = 1;
  return ele.splice(i, delLen);
}
function blocksFor() {
  let arr = [];
  mdTextParsee2(temp).forEach((element) => {
    let list = creatBlock(element, md.render(element));
    // console.log(list)
    arr.push(list);
  });
  return arr;
}

export default {
   name: 'laboratory',
  data() {
    return {
      blockElement: {
        selectIndex: 0, //当前元素节点位置
        target: {},
        targetMouseenterIndex: {},
        targetMouseenterDom: {},
        targetDom: {}, //dom
        targetDomPrevious: {}, //上一个节点
        targetDomNext: {}, //下一个节点
        blocks: blocksFor(),
      },
      tempText: "",
      fastSelectList: [
        { text: "文本", explana: "普通文字", imgUrl: "" },
        { text: "页面", explana: "链接新的页面", imgUrl: "" },
        { text: "列表", explana: "勾选框", imgUrl: "" },
        { text: "标题", explana: "如题所示", imgUrl: "" },
        { text: "符号列表", explana: "带符号的列表", imgUrl: "" },
        { text: "数字列表", explana: "带数字的列表", imgUrl: "" },
        { text: "代码块", explana: "各种语言代码块", imgUrl: "" },
        { text: "附件", explana: "pdf,txt,md文件等", imgUrl: "" },
        { text: "视频", explana: "mp4等视频格式", imgUrl: "" },
        { text: "图片", explana: "jpg,png,svg", imgUrl: "" },
      ],
    };
  },
  components: {
    OverlayContainer,
    // DropBox
  },
  // mounted: function() {   },
  methods: {
    hotKeyDirection(e, direction) {
      if (direction == "up") {
        console.log("上");
      }
    },
    slashHotKey(e) {
      if (e.keyCode == 191) {
        console.log("斜杠", e);
      }
    },
    //获取当前节点
    getMouseenter(e) {
      // return
      let targetDom = e.path.find((item) => {
        if (item.localName == "div" && item.getAttribute("contenteditable")) {
          this.blockElement.targetMouseenterIndex = Number(
            item.getAttribute("selectIndex")
          );
          return item;
        } //当前节点元素
      });
      if (targetDom) {
        this.blockElement.targetMouseenterDom = targetDom;
        setTimeout(() => {
          let index = this.blockElement.targetMouseenterIndex;
          this.blockElement.blocks[index][
            "menu"
          ] = `<b><a contenteditable='false' >:::::</a></b>`; //创建菜单
        }, 200);
      } else {
        this.removeMenu(); //离开了
      }
    },
    //键盘方向控制
    direction(e, d) {
      let { range, positionIndex, positionText } = cursor.base();
      console.log(range, positionIndex, positionText);
      if (d == "up" && positionIndex == 0) {
        cursor.SetCursorPosition(this.blockElement.targetDomPrevious, 1, 1);
      } else if (d == "down" && positionIndex == positionText.length) {
        //下
      
        this.blockElement.targetDomNext.focus();
      }
    },
    //删除
    keyupBackspaceDelete(e) {
      let { range, positionIndex, positionText } = cursor.base();
      // console.log(range, positionIndex, positionText)
      if (this.blockElement.targetDom.innerText == "\n") {
        this.blockElement.targetDom.innerText = "";
      }
      let positionTextLen = positionText.length;
      if (e.keyCode == 46) {
        // 后
        if (positionIndex == positionTextLen) {
          //光标在尾部的时候
          this.blockElement.targetDomNext.focus(); //光标跳转到下一节点的首部
          // cursor.SetCursorPosition(this.blockElement.targetDomNext); //光标跳转到文本末尾
        }
        return;
      }
      if (
        this.blockElement.target.html == "" &&
        this.blockElement.selectIndex != 0
      ) {
        cursor.SetCursorPosition(this.blockElement.targetDomPrevious, 1, 1);
        delEle(this.blockElement.blocks, this.blockElement.selectIndex + 1); //删除节点
      } else if (!this.blockElement.targetDom.hasChildNodes()) {
        //没有节点了就删除
        this.blockElement.target.html = "";
        this.blockElement.target.placeholder = "输入 / 选择类型";
        //  console.log()
      } else if (
        range.startOffset == 0 &&
        (range.startContainer.nodeName == "DIV" ||
          range.startContainer.nodeName == "DT")
      ) {
        //光标在节点首部,跳到上一个节点
        cursor.SetCursorPosition(this.blockElement.targetDomPrevious, 1, 1); //光标移动
      }
      return;
    },
    removeMenu() {
      this.blockElement.blocks = this.blockElement.blocks.map((item) => {
        return {
          ...item,
          menu: "",
        };
      });
    },
    //获取焦点
    getInputFocus(e) {
      // console.log("获取焦点成功",cursor.base());
      this.blockElement.targetDom = e.target;
      this.blockElement.selectIndex = Number(
        e.target.getAttribute("selectIndex")
      );
      this.blockElement.target = this.blockElement.blocks[
        this.blockElement.selectIndex
      ];
      let parentElement = this.blockElement.targetDom.parentElement;
      //获取上一个节点
      const firstNode = 0;
      this.blockElement.targetDomPrevious =
        parentElement.children[this.blockElement.selectIndex - 1] ||
        parentElement.children[firstNode];
      //获取下一个节点
      this.blockElement.targetDomNext =
        parentElement.children[this.blockElement.selectIndex + 1] ||
        parentElement.children[parentElement.children.length - 1];
    },

    //回车按键换行
    keydownEnter(e) {
      // console.log(cursor.base())
      if (e.shiftKey) {
        return true;
      } else {
        event.returnValue = false;
        const add = 0;
        let addEle = creatBlock(`&nbsp;\n`, "&nbsp;\n");
        this.blockElement.target; //没有获取到目标焦点
        this.blockElement.target.html = this.blockElement.target.html.replace(
          /(.*)<br>/,
          ""
        );
        this.blockElement.blocks.splice(
          this.blockElement.selectIndex + 1,
          add,
          addEle
        );
        setTimeout(() => {
          cursor.SetCursorPosition(
            this.blockElement.targetDom.nextSibling,
            1,
            1
          );
          document.execCommand("delete", false, null);
        }, 1);
      }
    },
    //添加文本
    mdRender() {
      this.blockElement.blocks.push(
        creatBlock(this.tempText, md.render(this.tempText))
      );
    },
  },
};
</script>
<style lang="scss" >
.hot-key-select-list {
  box-shadow: 0 1px 45px -3px rgba(108, 108, 108, 0.4) max-width 300px margin auto;
}
.hot-key-select-block {
  padding: 5px 0 5px 0;
  display: flex;
}
.hot-key-select-block:hover {
  background: rgba(96, 90, 73, 0.1);
}
.markdown-body {
  .list-menu {
    width: 45px;
    margin-left: -45px;
    top: 0;
    position: absolute;
    background #EEE a {
      float: left;
    }
  }
  .block-node {
    position: relative;
    outline: none;
    svg {
      width: 100%;
    }
  }

  .block-node:empty::before {
    color: #aaa;
    content: attr(placeholder);
  }

  pre.hljs {
    padding: 8px 10px;
    border-radius: 5px;
    position: relative;

    ol {
      list-style: decimal;
      margin: 0;
      margin-left: 40px;
      padding: 0;

      li {
        list-style: decimal;
        position: relative;
        padding-left: 10px;

        .line-num {
          position: absolute;
          left: -40px;
          top: 0;
          width: 40px;
          height: 100%;
          border-right: 1px solid rgba(177, 170, 170, 0.66);
        }
      }
    }
  }
}
</style> 